package cn.caplike.demo.spring.security.dynamic.authorization.service;

import cn.caplike.demo.spring.security.dynamic.authorization.domain.dto.CustomUserDetailsDto;
import cn.caplike.demo.spring.security.dynamic.authorization.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * UserDetailsService 的实现
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-05-07 11:04
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private static final String USERNAME_NOT_FOUND_MESSAGE = "User with name (%s) not exists.";

    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new CustomUserDetailsDto(
                Optional.ofNullable(userMapper.getUserRoleDto(username)).orElseThrow(() -> new UsernameNotFoundException(String.format(USERNAME_NOT_FOUND_MESSAGE, username)))
        );
    }

    // ~ Autowired
    // -----------------------------------------------------------------------------------------------------------------

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
